package xkp.lesson3;

public class 二分查找 {
	 public static void main(String[] args) {
	        int[] arr = {1,4,7,10,13,15,21,25};
	        int index = binarySearch(arr,12);
	        System.out.println(index);
	        index = binarySearch(arr,7);
	        System.out.println(index);
	    }

	    public static int binarySearch(int[] arr,int key) {
	        //定义三个索引位置。
	        int min = 0;
	        int max = arr.length - 1;
	        int mid = 0;
	        //循环折半，条件， min<=max
	        while(min <= max) {
	            //公式，计算中间索引
	            mid = (min+max)/2;
	            //让被找元素和中间索引元素进行比较
	            if(key>arr[mid]) {
	                min = mid +1;
	            }else if(key <arr[mid]) {
	                max = mid -1;
	            }else {
	                //找到元素，返回元素索引
	                return mid;
	            }
	        }
	        return -1;
	    }
}
